from django.contrib import admin
from django.contrib.auth.hashers import make_password

from user.models import *
from import_export import resources


class UserControl(admin.ModelAdmin):
    pass


class StudentResource(resources.ModelResource):

    class Meta:
        model = Student
        fields = ('id', 'user', 'clazz')
        export_order = fields
        import_id_fields = fields


@admin.register(Clazz)
class ClazzAdmin(admin.ModelAdmin):
    list_display = ('clazz_name', 'stu_num', 'manager_num')
    list_filter = ('clazz_name',)
    search_fields = ('clazz_name', )

    def stu_num(self, obj):
        return Student.objects.filter(clazz__clazz_name=obj.clazz_name).count()

    def manager_num(self, obj):
        return Manager.objects.filter(clazzs__clazz_name=obj.clazz_name).count()

    stu_num.short_description = '学生数量'
    manager_num.short_description = '管理员数量'


@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
    list_display = ('user', 'man_clazzs')

    def man_clazzs(self, obj):
        clazz_objs = Clazz.objects.filter(manager__user__username=obj.user.username)
        clazzs = []
        for i in clazz_objs:
            clazzs.append(i)
        return clazzs

    man_clazzs.short_description = '管理班级'


@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
    fields = ('clazz', 'user')
    list_display = ('username', 'real_name', 'clazz')
    list_display_links = ('username', )
    list_filter = ('clazz__clazz_name',)
    ordering = ['user__username', ]
    search_fields = ('clazz__clazz_name', 'user__username', 'user__first_name')

    def username(self, obj):
        return obj.user.username

    def real_name(self,obj):
        return obj.user.first_name

    username.short_description = '学号'
    real_name.short_description = '姓名'


@admin.register(CustomUser)
class CustomUserAdmin(admin.ModelAdmin):

    fields = ('username', 'password', 'first_name')
    list_display = ('username', 'first_name', 'student_status', 'manager_status')
    search_fields = ('username', 'first_name')

    def student_status(self, obj):
        if Student.objects.filter(user__username=obj.username):
            return '是'
        else:
            return '否'

    def manager_status(self, obj):
        if Manager.objects.filter(user__username=obj.username):
            return '是'
        else:
            return '否'

    manager_status.short_description = '管理员'
    student_status.short_description = '学生'

    def save_model(self, request, obj, form, change):
        if not form.data['password'].startswith('pbkdf2_sha256'):
            obj.password = make_password(form.data['password'])
        super().save_model(request, obj, form, change)


